package com.weipeep.sys.service.impl;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.weipeep.sys.dao.MottoDao;
import com.weipeep.sys.domain.MottoDO;
import com.weipeep.sys.service.MottoService;
import com.weipeep.common.base.CoreServiceImpl;
import org.springframework.util.StopWatch;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 
 * <pre>
 * 
 * </pre>
 * <small> 2018-12-19 14:58:39 | wangyun</small>
 */
@Service
public class MottoServiceImpl extends CoreServiceImpl<MottoDao, MottoDO> implements MottoService {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    private ExecutorService executorService = Executors.newFixedThreadPool(3);
    @Resource
    DruidDataSource druidDataSource;

    @Override
    public void testConnection(int index) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        long starttime = System.currentTimeMillis();
        executorService.execute(()->{
            StopWatch stopWatchInner = new StopWatch();
            stopWatchInner.start();
            long calltime = starttime;
            if(System.currentTimeMillis()-calltime < 3000) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            DruidPooledConnection druidPooledConnection = null;
            try {
                druidPooledConnection = druidDataSource.getConnection();
                Thread.sleep(100);
                stopWatchInner.stop();
                log.info("-----task{}------finish time:{}------connection:{}--------",index,stopWatchInner.getTotalTimeMillis(),druidPooledConnection.toString());
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (druidPooledConnection !=null){
                        druidPooledConnection.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });
        stopWatch.stop();
        log.info("-----task{}------start time:{}--------------",index,stopWatch.getTotalTimeMillis());
    }

    @Override
    @Async
    public void task1(long time) {
        log.info("-----task1--------{}",time);
    }
}
